<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="患者姓名" prop="patientId">
        <el-input
            v-model="queryParams.patientId"
            placeholder="请输入患者姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="就诊卡号" prop="medicalCardNumber">
        <el-input
            v-model="queryParams.medicalCardNumber"
            placeholder="请输入就诊卡号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="idCardNumber">
        <el-input
            v-model="queryParams.idCardNumber"
            placeholder="请输入身份证号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phoneNumber">
        <el-input
            v-model="queryParams.phoneNumber"
            placeholder="请输入手机号码"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="体检套餐名称" prop="packageName">
        <el-input
            v-model="queryParams.packageName"
            placeholder="请输入体检套餐名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="套餐费用" prop="packageFee">
        <el-input
            v-model="queryParams.packageFee"
            placeholder="请输入套餐费用"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="体检日期" prop="examDate">
        <el-date-picker clearable
                        v-model="queryParams.examDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择体检日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="预约时间" prop="appointmentTime">
        <el-date-picker clearable
                        v-model="queryParams.appointmentTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择预约时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="记录创建时间" prop="createdAt">
        <el-date-picker clearable
                        v-model="queryParams.createdAt"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择记录创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:examinations:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:examinations:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:examinations:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:examinations:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="examinationsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="患者姓名" align="center" prop="patientId" />
      <el-table-column label="就诊卡号" align="center" prop="medicalCardNumber" />
      <el-table-column label="身份证号" align="center" prop="idCardNumber" />
      <el-table-column label="手机号码" align="center" prop="phoneNumber" />
      <el-table-column label="体检套餐名称" align="center" prop="packageName" />
      <el-table-column label="套餐费用" align="center" prop="packageFee" />
      <el-table-column label="状态(待体检/已完成/已退款)" align="center" prop="status" />
      <el-table-column label="体检日期" align="center" prop="examDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.examDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约时间" align="center" prop="appointmentTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.appointmentTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="记录创建时间" align="center" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="() => handleUpdate(scope.row)" v-hasPermi="['system:examinations:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="() => handleDelete(scope.row)" v-hasPermi="['system:examinations:remove']">删除</el-button>
          <el-button link type="primary" icon="View" @click="() => handleDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改预约体检记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="examinationsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="患者姓名" prop="patientId">
          <el-select v-model="form.patientId" placeholder="请选择患者" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in patientsList" :key="index" :value="item.id"
                       :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="就诊卡号" prop="medicalCardNumber">
          <el-input v-model="form.medicalCardNumber" placeholder="请输入就诊卡号" disabled/>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCardNumber">
          <el-input v-model="form.idCardNumber" placeholder="请输入身份证号" disabled/>
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入手机号码" disabled/>
        </el-form-item>
        <el-form-item label="体检套餐名称" prop="packageName">
<!--          <el-input v-model="form.packageName" placeholder="请输入体检套餐名称" />-->
          <el-select v-model="form.packageName" placeholder="请输入体检套餐名称" clearable :style="{width: '100%'}">
            <el-option
                :label="item.packageName"
                :value="item.id"
                :key="index"
                v-for="(item,index) in packagelist"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="套餐费用" prop="packageFee">
          <el-input v-model="form.packageFee" placeholder="请输入套餐费用" disabled/>
        </el-form-item>
        <el-form-item label="体检日期" prop="examDate">
          <el-date-picker clearable
                          v-model="form.examDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择体检日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预约时间" prop="appointmentTime">
          <el-date-picker clearable
                          v-model="form.appointmentTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择预约时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="记录创建时间" prop="createdAt">
          <el-date-picker clearable
                          v-model="form.createdAt"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择记录创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
                v-for="(item, index) in statuslist"
                :key="index"
                :label="item.label"
            >{{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </template>
    </el-dialog>

    <el-dialog title="体检详情" v-model="detailOpen" width="700px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="患者姓名">{{ detailData.patientId }}</el-descriptions-item>
        <el-descriptions-item label="就诊卡号">{{ detailData.medicalCardNumber }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ detailData.idCardNumber }}</el-descriptions-item>
        <el-descriptions-item label="手机号码">{{ detailData.phoneNumber }}</el-descriptions-item>
        <el-descriptions-item label="体检套餐名称">{{ detailData.packageName }}</el-descriptions-item>
        <el-descriptions-item label="套餐费用">{{ detailData.packageFee }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ detailData.status }}</el-descriptions-item>
        <el-descriptions-item label="体检日期">{{ detailData.examDate }}</el-descriptions-item>
        <el-descriptions-item label="预约时间">{{ detailData.appointmentTime }}</el-descriptions-item>
        <el-descriptions-item label="记录创建时间">{{ detailData.createdAt }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailOpen = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Examinations">
import { listExaminations, getExaminations, delExaminations, addExaminations, updateExaminations } from "@/api/system/examinations"
import {listPackage,getPackage} from "@/api/system/package.js"
import {watch} from "vue";
import { listPatients,getPatients } from "@/api/system/patients.js"
import {values} from "lodash";

const { proxy } = getCurrentInstance()

const examinationsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const detailOpen = ref(false)
const detailData = ref({})
const statuslist = ref([
  {
    label: "待体检",
    value: "0"
  },
  {
    label: "已完成",
    value: "1"
  },
  {
    label: "已退款",
    value: "2"
  }
])

//所有的
const packagelist = ref([])
//各自的
const packageitem = ref([])
//患者信息
const patientsList = ref([])
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    patientId: null,
    medicalCardNumber: null,
    idCardNumber: null,
    phoneNumber: null,
    packageName: null,
    packageFee: null,
    status: null,
    examDate: null,
    appointmentTime: null,
    createdAt: null
  },
  rules: {
    patientId: [
      { required: true, message: "患者姓名不能为空", trigger: "blur" }
    ],
    medicalCardNumber: [
      { required: true, message: "就诊卡号不能为空", trigger: "blur" }
    ],
    idCardNumber: [
      { required: true, message: "身份证号不能为空", trigger: "blur" }
    ],
    phoneNumber: [
      { required: true, message: "手机号码不能为空", trigger: "blur" }
    ],
    packageName: [
      { required: true, message: "体检套餐名称不能为空", trigger: "blur" }
    ],
    packageFee: [
      { required: true, message: "套餐费用不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态(待体检/已完成/已退款)不能为空", trigger: "change" }
    ],
    examDate: [
      { required: true, message: "体检日期不能为空", trigger: "blur" }
    ],
    appointmentTime: [
      { required: true, message: "预约时间不能为空", trigger: "blur" }
    ],
    createdAt: [
      { required: true, message: "记录创建时间不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)
watch(() => form.value.packageName, async (newValue, oldValue) => {
  // 在这里执行你想要的操作，比如根据新的院区获取对应的科室
  if (newValue) {
    form.value.packageFee=(await getPackage(newValue)).data.price
    // form.value.packageFee=getPackage(newValue).data.price
  }
});
watch(() => form.value.patientId, async (newValue, oldValue) => {
  // 在这里执行你想要操作的
  if (newValue) {
    form.value.medicalCardNumber=(await getPatients(newValue)).data.cardNo
    form.value.idCardNumber=(await getPatients(newValue)).data.idCard
    form.value.phoneNumber=(await getPatients(newValue)).data.phone
  }
});
/** 查询预约体检记录列表 */
function getList() {
  loading.value = true
  listExaminations(queryParams.value).then(async response => {
    examinationsList.value = response.rows
    let examinationsList1 =response.rows
    console.log(examinationsList1)
    for (var i = 0; i < examinationsList.value.length; i++) {
      examinationsList.value[i].packageName = (await getPackage(examinationsList1[i].packageName)).data.packageName
    }
    for (var j = 0; j < examinationsList.value.length; j++){
      examinationsList.value[j].phoneNumber = (await getPatients(examinationsList1[j].patientId)).data.phone
      examinationsList.value[j].idCardNumber = (await getPatients(examinationsList1[j].patientId)).data.idCard
      examinationsList.value[j].medicalCardNumber = (await getPatients(examinationsList1[j].patientId)).data.cardNo
      examinationsList.value[j].patientId = (await getPatients(examinationsList1[j].patientId)).data.name
    }
    total.value = response.total
    loading.value = false
  })
   listPackage().then(response => {
    packagelist.value = response.rows
  })
  listPatients().then(response => {
    patientsList.value = response.rows
    console.log(response.rows)
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    patientId: null,
    medicalCardNumber: null,
    idCardNumber: null,
    phoneNumber: null,
    packageName: null,
    packageFee: null,
    status: null,
    examDate: null,
    appointmentTime: null,
    createdAt: null
  }
  proxy.resetForm("examinationsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加预约体检记录"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getExaminations(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改预约体检记录"
  })
}

/** 提交按钮 */
function submitForm() {
  console.log(form.value)
  proxy.$refs["examinationsRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateExaminations(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addExaminations(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除预约体检记录编号为"' + _ids + '"的数据项？').then(function() {
    return delExaminations(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/examinations/export', {
    ...queryParams.value
  }, `examinations_${new Date().getTime()}.xlsx`)
}

function handleDetail(row) {
  detailData.value=row
  detailOpen.value = true
}
onActivated(()=>{
  getList()
})
getList()
</script>
